var $bw = {};
/**
 * 外部资源引入 css
 * @author duantingting@bestwise.cc 2017-01-09
 * @param  {[type]} url [description]
 * @return {[type]}     [description]
 */
$bw.loadCss = function(url) {
  var head = document.getElementsByTagName('head');
  if (head && head.length) {
    head = head[0];
  } else {
    head = document.body;
  }
  var link = document.createElement('link');
  link.rel = "stylesheet";
  head.appendChild(link);
  link.onload = link.onreadystatechange = function() {
    /*if ((!this.readyState) || this.readyState == "complete" || this.readyState == "loaded") {}*/
  };
  link.href = url;
}

/**
 * 外部资源引入 js
 * @author duantingting@bestwise.cc 2017-01-19
 * @param  {[type]}   url      [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
$bw.loadJS = function(url, callback) {
  var head = document.getElementsByTagName('head');
  if (head && head.length) {
    head = head[0];
  } else {
    head = document.body;
  }
  var script = document.createElement('script');

  script.type = "text/javascript";
  head.appendChild(script);

  script.onload = script.onreadystatechange = function() {
    if ((!this.readyState) || this.readyState == "complete" || this.readyState == "loaded") {
      if (callback) callback();
    }
  };
  script.src = url;
}

/**
 * 替换所有
 * @Author duan     2017-09-15T13:43:56+0800
 * @param  {[type]} str                      [description]
 * @param  {[type]} s1                       [description]
 * @param  {[type]} s2                       [description]
 * @return {[type]}                          [description]
 */
$bw.replaceAll = function(str, s1, s2) {
  if (typeof(str) == 'string') {
    return str.replace(new RegExp(s1, "gm"), s2);
  } else {
    return str;
  }
};

/**
 * 获取对象长度
 * @author duantingting@bestwise.cc 2017-01-19
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
$bw.getLength = function(obj) {
  var n = 0;
  for (var i in obj) { n++; }
  return n;
};
/**
 * 获取url参数
 * @author duantingting@bestwise.cc 2017-01-19
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
$bw.getUrlInfo = function(name) {
  var href=decodeURI(window.document.location.href);
  var url=href.substr(parseInt(href.indexOf('?'))+1);

  if (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = url.match(reg);
    if (r !== null) return unescape(r[2]);
    return null;
  } else {
    if (typeof(url) == "string" && url.length > 0) {
      var u = url.split("&"),
        getInfo = {},
        j = '';
      for (var i in u) {
        j = u[i].split("=");
        getInfo[j[0]] = j[1];
      }
      return getInfo;
    }
    return {};
  }
};
/**
 * 获取url文件名
 * @author duantingting@bestwise.cc 2017-01-19
 */
$bw.GetPageName = function() {
  var url = window.location.href; //获取完整URL
  var tmp = new Array(); //临时变量，保存分割字符串
  tmp = url.split("/"); //按照"/"分割
  var pp = tmp[tmp.length - 1]; //获取最后一部分，即文件名和参数
  tmp = pp.split("?"); //把参数和文件名分割开
  return tmp[0];
};
/**
 * 日期转时间戳
 * @author duantingting@bestwise.cc 2017-04-17
 * @param  {[type]} date [description]
 * @return {[type]}      [description]
 */
function dateToNum(dateStr) {
  return Date.parse(new Date(dateStr));
}
/**
 * 时间戳转换
 * @Author duan     2017-09-15T13:44:23+0800
 * @param  {[type]} shijianchuo              [description]
 * @param  {[type]} type                     [description]
 * @return {[type]}                          [description]
 */
$bw.format = function(shijianchuo, type) {
  if (!shijianchuo) return '';
  //shijianchuo是整数，否则要parseInt转换
  var time = new Date(parseInt(shijianchuo));
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  var add0 = function(m) {
    return m < 10 ? '0' + m : m;
  };
  switch(type){
    case 'minDay':
      return y + '-' + add0(m) + '-' + '01';
      break;
    case 'date':
      return y + '-' + add0(m) + '-' + add0(d);
      break;
    case 'time':
      return add0(h) + ':' + add0(mm);
      break;
    case 'second':
      return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
      break;
    case 'month':
      return y + '-' + add0(m);
      break;
    case 'dateTime':
      return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm);
      break;
    default:
      return {y:add0(y),m:add0(m),d:add0(d),h:add0(h),mm:add0(mm),s:add0(s)}
  }
}

//写入Cookie缓存 时间以秒计算
$bw.addStorage = function(obj) {
  //如果不规定生命周期 默认一年
  // if (!obj.livetime) { obj.livetime = 60 * 60 * 24 * 365; }
  if (!obj.livetime) { obj.livetime = 15 * 60 * 60; }
  var msg = {
    info: obj.info,
    time: new Date().getTime(),
    livetime: obj.time
  };
  localStorage[obj.name] = JSON.stringify(msg);
}
//取Cookie缓存
$bw.getStorage = function(name) {
  var msg = null;
  if (typeof(localStorage[name]) == 'undefined' || localStorage[name] === null || localStorage[name] == 'null') {
    return null;
  } else {
    msg = JSON.parse(localStorage[name]);
    if (!msg.info || msg.info === null || msg.info.length === 0) return null;
  }
  if (msg.time + msg.livetime * 1000 < new Date().getTime()) return null;
  return msg.info;
}
//写入session缓存 时间以秒计算
$bw.addSession = function(obj) {
  var msg = {
    info: obj.info,
    time: new Date().getTime(),
    livetime: obj.time
  };
  sessionStorage[obj.name] = JSON.stringify(msg);
}
//取session缓存
$bw.getSession = function(name) {
  var msg = null;
  if (typeof(sessionStorage[name]) == 'undefined' || sessionStorage[name] === null || sessionStorage[name] === 'null') {
    return null;
  } else {
    msg = JSON.parse(sessionStorage[name]);
    if (!msg.info || msg.info === null || msg.info.length === 0) return null;
  }
  if (msg.livetime) {
    if (msg.time + msg.livetime * 1000 < new Date().getTime()) return null;
  }
  return msg.info;
}
/**
 * 判断是否在数组内
 * @Author duan     2017-09-15T13:45:55+0800
 * @param  {[type]} val                      [description]
 * @param  {[type]} arr                      [description]
 * @return {[type]}                          [description]
 */

$bw.inArray = function(val, arr) {
  for (var i in arr) {
    if (arr[i] === val) {
      return true;
    }
  }
  return false;
}
/**
 * 四舍五入保留N位小数
 * @Author duan     2017-09-15T13:46:10+0800
 * @param  {[type]} info                     [description]
 * @param  {[type]} num                      [description]
 * @return {[type]}                          [description]
 */
$bw.tofixed = function(num, n) {
  if (!num) return 0;
  num = parseFloat(num);
  if (!n) n = 2;
  return num.toFixed(n);
}
/**
 * 验证用户登录
 * @author duantingting@bestwise.cc 2017-01-24
 * @return {[type]}       [description]
 */
$bw.verifyLogin = function() {
  var userInfo = $bw.getSession('userSessionInfo');
  if (userInfo === null) {
    userInfo = $bw.getStorage('userSessionInfo');
    $bw.addSession({ name: 'userSessionInfo', info: userInfo });
  }
  if (userInfo === null) {
    return false;
  } else {
    $bw.userInfo = userInfo;
    return true;
  }
}
$bw.uploadFile = function(files) {
  return new Promise((resolve, reject) => {
    var formData = new FormData();
    formData.append('file', files[0]);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", $C.httpHeader + '/File/UpLoadMultipleFiles');
    xhr.setRequestHeader("Authorization", "Bearer " + $bw.userInfo.token);
    xhr.send(formData);
    xhr.onreadystatechange = function() {

      if (xhr.readyState == 4 && xhr.status == 200) {
        var blkRet = JSON.parse(xhr.responseText);
        resolve(blkRet);
      } else if (xhr.readyState == 4 && xhr.status != 200) {
        reject(xhr.responseText);
      }
    }
  })
}

export default $bw
